import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {ParentService} from "@train/parent/parent.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {TrainStudent} from "@interface/index";
import {ToolsService} from "@shared/service/tools/tools.service";
import {TrainService} from "@train/train.service";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {ValidationService} from "@shared/service/validator/validator.service";
import {AuthService} from "@shared/service/auth/auth.service";


@Component({
  selector: 'seed-child-detail',
  templateUrl: './child-detail.component.html',
  styleUrls: ['./child-detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TrainChildDetailComponent implements OnInit {
  public saving = false;
  public defaulticon;
  public params = {
    studentId : '',
    orgUserId: ''
  };
  public hasChange = false;
  public studentInfo: TrainStudent = new TrainStudent();
  public form: FormGroup;
  private picTemp = '';
  constructor(
    private route: ActivatedRoute,
    private _parentService: ParentService,
    private _fb: FormBuilder,
    public _tools: ToolsService,
    public _trainSer: TrainService,
    private imgService: ImageServeService,
    private _auth: AuthService
  ) {
    this._tools.setTitle('学员档案');
    this.defaulticon = this.imgService.getUserIcon();
    this.route.params.subscribe((params: Params) => {
      this.params.studentId = params['studentId'];
      this.params.orgUserId = _auth.getAuthOrgId();
      this.fetchStudent(this.params);
    });
  }
  /**
   * @desc 页面表单初始化
   * @author ouxh
   * @time 2018/1/29
   */
  formInit() {
    this.form = this._fb.group({
      sex: [''],
      parentName: [''],
      birthday: [''],
    });
    this.form.valueChanges.subscribe(form => {
      this.hasChange = true;
      // console.log(this.form);
    });
  }
  /**
   * @desc 获取学员信息
   * @author ouxh
   * @time 2018/1/29
   */
  fetchStudent(params) {
    this._parentService.findStudentInfo(params)
      .filter(res => res.result === '0')
      .subscribe(res => {
        this.studentInfo = res.data;
        if (res.data.birthday) {
          this.form.controls['birthday'].setValue(this.getDateStr(res.data.birthday));
        }
        if (res.data.sex >= 0) {
          this.form.controls['sex'].setValue(res.data.sex);
        }
        if (res.data.parentName) {
          this.form.controls['parentName'].setValue(res.data.parentName);
        }
      });
  }

  /**
   * @desc 时间戳转换成 2011-10-10
   * @author ouxh
   * @time 2018/1/26
   * @param {string} timeStamp 表示往前或者往后的多少周
   */
  getDateStr(timeStamp: string) {
    return timeStamp && this._tools.dateTostr(new Date(timeStamp));
  }
  submit() {
    if (this.saving) {
      return;
    }
    const form = this.form.value;
    if (!form.parentName.match(/^[\u4e00-\u9fa5A-Za-z]*$/) || form.parentName.length > 40) {
      this._tools.showToast('姓名请输入0-40个汉字或字母');
      return;
    }
    this.saving = true;
    const data = {
      id: this.params.studentId,
      orgUserId: this.params.orgUserId
    };
    Object.keys(form).forEach(key => {
      switch (key) {
        case  'sex' :
          data['sex'] = form.sex;
          break;
        case 'birthday':
          data['birthdayTimeStamp'] = form.birthday ? new Date(form.birthday).getTime() : '';
          break;
        case 'parentName':
          data['parentName'] = form.parentName;
          break;
      }
    });
    this._tools.showLoading();
    this._parentService.updateStudentInfo(data)
      .subscribe(res => {
        this._tools.hideLoading();
        this.saving = false;
        if (res.result === '0') {
          this._tools.showToast('信息更新成功');
          setTimeout(() => {
            history.back();
          }, 1500);
        }else {
          this._tools.showToast(res.msg);
        }
      });
  }

  /**
   * @desc 上传头像
   * @author ouxh
   * @time 2018/1/26
   * @param {e} event
   */
  addPicture(e) {
    this._tools.showLoading();
    this._trainSer.upLoadFile(e.target.files[0]).subscribe((res) => {
      if (res.result === '0' && res.data) {
        const data = {
          id: this.params.studentId,
          headPicture: res.data[0],
          orgUserId: this.params.orgUserId
        };
        this.picTemp = res.data[0];
        this._parentService.updateStudentInfo(data)
          .subscribe(resp => {
            this._tools.hideLoading();
            if (resp.result === '0') {
              // this.studentInfo.headPicture = '';
              // setTimeout(() => {
                this.studentInfo.headPicture = this.picTemp;
              // });
              this._tools.showToast('头像更新成功');
            }else {
              this._tools.showToast(res.msg);
            }
          });
      }else {
        this._tools.hideLoading();
        this._tools.showToast(res.msg);
      }
    });
  }
  ngOnInit() {
    this.formInit();
  }

}
